<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
abstract class DMHTTPResponseFactory {

	private static function getBestRepresentation(DMHTTPRequest $req) {
		$route = $req->getURI()->getRoute();
		$best_rep = null;
		if ($route) {
			$best_rep = $route->getBestRepresentation(
					$req->getURI()->getExtension());
		} else {
			$best_rep = $req->getURI()->getExtension();
			if (!$best_rep) {
				$best_rep = $req->getURI()->isHTTPAPI() ? "xml" : "html";
			}
		}
		return $best_rep;
	}

	/**
	 * @return DMHTTPResponse
	 */
	public static function getRepresentation() {
		$type = new DMMediaType("text", "plain");
		$best_rep = self::getBestRepresentation(DMHTTPRequest::getCurrent());

		switch ($best_rep) {
		case "atom":
			$type = new DMMediaType("application", "atom+xml");
			break;
		case "html":
			$type = new DMMediaType("text", "html");
			break;
		case "json":
			$type = new DMMediaType("application", "json");
			break;
		case "jsonp":
			$type = new DMMediaType("text", "javascript");
			break;
		case "sitemap":
			$type = new DMMediaType("application", "xml");
			break;
		case "xml":
			$type = new DMMediaType("application", "xml");
			break;
		}

		$rep = new DMHTTPRepresentation();
		$rep->setMediaType($type);
		return $rep;
	}

	/**
	 * @return DMHTTPAPIRepresentationTransformer
	 */
	public static function getTransformer() {
		$version = DMHTTPRequest::getCurrent()->getURI()->getVersion();
		$version = $version
			? $version : DMBridgeVersion::getLatestHTTPAPIVersion();

		$best_rep = self::getBestRepresentation(DMHTTPRequest::getCurrent());

		switch ($best_rep) {
		case "atom":
			return new DMAtomRepresentationTransformer();
			break;
		case "json":
			$class = 'DMJSONRepresentationTransformerV' . $version;
			return new $class;
			break;
		case "jsonp":
			$class = 'DMJSONPRepresentationTransformerV' . $version;
			return new $class;
			break;
		case "sitemap":
			return new DMSitemapRepresentationTransformer();
			break;
		case "xml":
			$class = 'DMXMLRepresentationTransformerV' . $version;
			return new $class;
			break;
		}
		return null;
	}

}
